import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:thingskit/components/lightContent.dart';
import 'package:thingskit/components/titleCard.dart';
import 'package:thingskit/utils/UsbController.dart';

import '../../apiService/mode.dart';
import '../../components/aRowBottons.dart';
import '../../components/constantButton.dart';
import '../../components/functionButton.dart';
import '../../components/selectBox.dart';
import '../../components/singleRowCard.dart';
import '../../utils/ToastController.dart';
import '../../utils/const.dart';

class FastSettingController extends GetxController {
  RxList<Mode> modes = <Mode>[].obs;
  var _selectedGroup = '请选择分组'.obs;
  var _selectedAddress=''.obs;
  var brightness = 0.0.obs;

  @override
  void onInit() {
    getModes();
    super.onInit();
  }

  //获取方案列表
  Future<void> getModes() async {
    EasyLoading.show(status: '加载中...', maskType: EasyLoadingMaskType.black);
    try {
      modes.value = await ModeApi().getModeList();
    } catch (e) {
      EasyLoading.showError('加载失败');
    } finally {
      EasyLoading.dismiss();
    }
  }
}



class FastSettingPage extends StatelessWidget {
  final UsbController usbController = Get.find();
  final toastController = Get.find<ToastController>();
  final FastSettingController FSC = Get.put(FastSettingController());



  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Obx(
                () => ARowBottons(
                  title1: usbController.isDebugging.value ? '关闭串口调试' : '开启串口调试',
                  color1:
                      usbController.isDebugging.value
                          ? Colors.red
                          : Colors.green,
                  onPressed1: usbController.openSerialPortDebug,
                  title2: '上下翻转',
                  color2: Colors.purple,
                  onPressed2: usbController.turnOver,
                ),
              ),
              Row(
                children: [
                  Expanded(
                    child: Row(
                      children: [
                        Text('分组', style: TextStyle(fontSize: 18)),
                        SizedBox(width: 10),
                        SelectBox(
                          initialValue: FSC._selectedGroup.value,
                          options: groupOptions,
                          label: '请选择分组',
                          onChanged: (value) {
                            FSC._selectedGroup.value = value;
                          },
                        ),
                      ],
                    ),
                  ),
                  SizedBox(width: 10),
                  Expanded(
                    child: FunctionButton(
                      onPressed: usbController.searchLight,
                      title: '搜灯',
                      color: Colors.blue,
                    ),
                  ),
                ],
              ),
              SizedBox(
                height: 220,
                child: Obx(
                  () => ListView.builder(
                    itemCount: usbController.Lights.length,
                    itemBuilder: (context, index) {
                      final light = usbController.Lights[index];
                      return SingleRowCard(
                        content: LightContent(index: index),
                        isChecked: FSC._selectedAddress.value == light['addr'],
                        onCheckChange: (newValue) {

                          FSC._selectedAddress.value =
                                newValue == true ? light['addr'] : null;

                        },
                        onClick: () {
                          usbController.lightInfo(light['addr']);
                        },
                      );
                    },
                  ),
                ),
              ),
              SizedBox(height: 10),
              TitleCard(title: '灯光设置'),
              SizedBox(height: 10),
              Obx(()=> Text(
                '亮度调节：${FSC.brightness.value.toInt()}%',
                style: TextStyle(fontSize: 16),
              ),),
              Obx(()=>Slider(
                min: 0,
                max: 100,
                value: FSC.brightness.value,
                activeColor: Colors.blue,
                onChanged: (value) {
                  FSC.brightness.value = value;
                },
              )),
              SizedBox(height: 8),
              Row(
                children: [
                  Expanded(
                    child: ConstantButton(
                      title: '常亮',
                      onPressed: () {
                        if (FSC._selectedGroup.value  != '请选择分组' &&
                            FSC._selectedGroup.value .isNotEmpty) {
                          usbController.alwaysFlashGroup(FSC._selectedGroup.value );
                        } else if (FSC._selectedAddress.value.isNotEmpty) {
                          usbController.alwaysFlashLight(FSC._selectedAddress.value);
                        } else {
                          toastController.showCenterToast('请选择一个灯');
                        }
                      },
                    ),
                  ),
                  SizedBox(width: 10),
                  Expanded(
                    child: ConstantButton(
                      title: '常灭',
                      onPressed: () {
                        if (FSC._selectedGroup.value != '请选择分组' &&
                            FSC._selectedGroup.value.isNotEmpty) {
                          usbController.closeFlashGroup(FSC._selectedGroup.value);
                        } else if (FSC._selectedAddress.value.isNotEmpty) {
                          usbController.closeFlashLight(FSC._selectedAddress.value);
                        } else {
                          toastController.showCenterToast('请选择一个灯或分组');
                        }
                      },
                    ),
                  ),
                  SizedBox(width: 10),
                  Expanded(
                    child: ConstantButton(
                      title: '感应',
                      onPressed: () {
                        if (FSC._selectedGroup.value != '请选择分组' &&
                            FSC._selectedGroup.value.isNotEmpty) {
                          usbController.setModeAutoGroup(FSC._selectedGroup.value);
                        } else if (FSC._selectedAddress.value.isNotEmpty) {
                          usbController.setModeAutoDevice(FSC._selectedAddress.value);
                        } else {
                          toastController.showCenterToast('请选择一个灯或分组');
                        }
                      },
                    ),
                  ),
                ],
              ),
              Row(
                children: [
                  Expanded(
                    child: ConstantButton(
                      title: '闪一闪',
                      onPressed: () {
                        if (FSC._selectedGroup.value != '请选择分组' &&
                            FSC._selectedGroup.value.isNotEmpty) {
                          usbController.flashGroup(FSC._selectedGroup.value);
                        } else if (FSC._selectedAddress.value.isNotEmpty) {
                          usbController.flash(FSC._selectedAddress.value);
                        } else {
                          toastController.showCenterToast('请选择一个灯或分组');
                        }
                      },
                    ),
                  ),
                  SizedBox(width: 10),
                  Expanded(
                    child: ConstantButton(
                      title: '停止闪',
                      onPressed: () {
                        if (FSC._selectedGroup.value != '请选择分组' &&
                            FSC._selectedGroup.value.isNotEmpty) {
                          usbController.stopFlashGroup(FSC._selectedGroup.value);
                        } else if (FSC._selectedAddress.value.isNotEmpty) {
                          usbController.stopFlash(FSC._selectedAddress.value);
                        } else {
                          toastController.showCenterToast('请选择一个灯或分组');
                        }
                      },
                    ),
                  ),
                  SizedBox(width: 10),
                  Expanded(
                    child: ConstantButton(
                      title: '下发亮度',
                      onPressed: () {
                        if (FSC._selectedGroup.value != '请选择分组' &&
                            FSC._selectedGroup.value.isNotEmpty) {
                          usbController.sendBrightnessGroup(
                            FSC._selectedGroup.value,
                            FSC.brightness.value.toInt() * 10,
                          );
                        } else if (FSC._selectedAddress.value.isNotEmpty) {
                          usbController.sendBrightnessLight(
                            FSC._selectedAddress.value,
                            FSC.brightness.value.toInt() * 10,
                          );
                        } else {
                          toastController.showCenterToast('请选择一个灯或分组');
                        }
                      },
                    ),
                  ),
                ],
              ),
              SizedBox(height: 10),
              TitleCard(title: '情景模式'),
              SizedBox(height: 10),
              if (FSC.modes.isEmpty) ...[
                Center(child: Text('暂无情景模式', style: TextStyle(fontSize: 20))),
              ] else ...[
                Obx(
                  () => Wrap(
                    spacing: 10.0, // 水平间距
                    runSpacing: 0, // 垂直间距
                    children:
                        FSC.modes
                            .map(
                              (mode) => ConstantButton(
                                onPressed: () {
                                  if (FSC._selectedGroup.value != '请选择分组' &&
                                      FSC._selectedGroup.value.isNotEmpty) {
                                    usbController.setGroupDevice(
                                      FSC._selectedGroup.value,
                                      jsonDecode(mode.content),
                                    );
                                  } else {
                                    if (FSC._selectedAddress.value.isNotEmpty) {
                                      usbController.setConfigDevice(
                                        FSC._selectedAddress.value,
                                        jsonDecode(mode.content),
                                      );
                                    } else {
                                      toastController.showCenterToast(
                                        '请选择一个灯或分组',
                                      );
                                    }
                                  }
                                },
                                title: mode.name,
                              ),
                            )
                            .toList(),
                  ),
                ),
              ],
            ],
          ),
        ),
    );
  }
}
